import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, Statistic, DatePicker, Button, Table, Form, Select, Divider } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取订单统计数据
const fetchOrderStatistics = async (params) => {
  return request('/api/v1/order/statistics', {
    method: 'GET',
    params,
  });
};

// 获取门店列表
const fetchStores = async () => {
  return request('/api/v1/store', {
    method: 'GET',
    params: { pageSize: 100, status: 1 },
  });
};

const OrderStatistics = () => {
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState({
    totalOrders: 0,
    totalAmount: 0,
    todayOrders: 0,
    todayAmount: 0,
    weekOrders: 0,
    weekAmount: 0,
    monthOrders: 0,
    monthAmount: 0,
    orderTrend: [],
    paymentTypeData: [],
    statusData: [],
  });
  const [stores, setStores] = useState([]);
  const [form] = Form.useForm();
  const [searchParams, setSearchParams] = useState({
    startDate: moment().subtract(30, 'days').format('YYYY-MM-DD'),
    endDate: moment().format('YYYY-MM-DD'),
  });

  // 获取统计数据
  const fetchStatisticsData = async () => {
    try {
      setLoading(true);
      const res = await fetchOrderStatistics(searchParams);
      if (res.success) {
        setStatistics(res.data || {});
      } else {
        console.error('获取订单统计数据失败:', res.msg);
      }
    } catch (error) {
      console.error('获取订单统计数据出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取门店列表
  const fetchStoreList = async () => {
    try {
      const res = await fetchStores();
      if (res.success) {
        setStores(res.data.list || []);
      } else {
        console.error('获取门店列表失败:', res.msg);
      }
    } catch (error) {
      console.error('获取门店列表出错:', error);
    }
  };

  useEffect(() => {
    fetchStatisticsData();
    fetchStoreList();
  }, [searchParams]);

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.dateRange && values.dateRange.length === 2) {
      params.startDate = values.dateRange[0].format('YYYY-MM-DD');
      params.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }
    if (values.storeId) {
      params.storeId = values.storeId;
    }

    setSearchParams(params);
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({
      startDate: moment().subtract(30, 'days').format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    });
  };

  // 订单状态分布表格列
  const statusColumns = [
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (text) => {
        switch (text) {
          case 1:
            return '待确认';
          case 2:
            return '已确认';
          case 3:
            return '已完成';
          case 4:
            return '已取消';
          case 5:
            return '已改签';
          default:
            return text;
        }
      },
    },
    {
      title: '订单数量',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (text) => `¥${(text / 100).toFixed(2)}`,
    },
    {
      title: '占比',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (text) => `${text}%`,
    },
  ];

  // 支付方式分布表格列
  const paymentColumns = [
    {
      title: '支付方式',
      dataIndex: 'type',
      key: 'type',
      render: (text) => {
        switch (text) {
          case 'wechat':
            return '微信支付';
          case 'alipay':
            return '支付宝';
          case 'balance':
            return '余额支付';
          case 'cash':
            return '现金支付';
          default:
            return text;
        }
      },
    },
    {
      title: '订单数量',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (text) => `¥${(text / 100).toFixed(2)}`,
    },
    {
      title: '占比',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (text) => `${text}%`,
    },
  ];

  return (
    <PageContainer>
      <Card style={{ marginBottom: 24 }}>
        <Form form={form} layout="inline" onFinish={handleSearch}>
          <Form.Item name="dateRange" label="日期范围" initialValue={[moment().subtract(30, 'days'), moment()]}>
            <RangePicker />
          </Form.Item>
          <Form.Item name="storeId" label="门店">
            <Select placeholder="请选择门店" style={{ width: 200 }} allowClear>
              {stores.map((store) => (
                <Option key={store.id} value={store.id}>
                  {store.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
            <Button 
              style={{ marginLeft: 8 }} 
              icon={<ReloadOutlined />} 
              onClick={fetchStatisticsData}
            >
              刷新
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Row gutter={24} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={statistics.totalOrders}
              precision={0}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ArrowUpOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总订单金额"
              value={(statistics.totalAmount / 100).toFixed(2)}
              precision={2}
              valueStyle={{ color: '#3f8600' }}
              prefix="¥"
              suffix=""
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日订单数"
              value={statistics.todayOrders}
              precision={0}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日订单金额"
              value={(statistics.todayAmount / 100).toFixed(2)}
              precision={2}
              valueStyle={{ color: '#1890ff' }}
              prefix="¥"
              suffix=""
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={24} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="订单状态分布">
            <Table
              columns={statusColumns}
              dataSource={statistics.statusData || []}
              rowKey="status"
              pagination={false}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="支付方式分布">
            <Table
              columns={paymentColumns}
              dataSource={statistics.paymentTypeData || []}
              rowKey="type"
              pagination={false}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default OrderStatistics;